/**
 * Created by Foold on 14-2-15.
 */

/*
 * GET users listing.
 */
var cname = require('path').basename(module.filename, '.js');
var routers = require('commons-dao')(cname);
var form = require('express-form');
var field = form.field;
var menuname = "mainmenu";
function getRules(i18n) {


    return [
        field('name').trim().required("", i18n.__('required', '名称'))
    ];

}


function addAndModify(req,res,pool,db,col) {
    var vbean = routers.xss(req.body);
    col.insert(vbean, {w: 1}, function (err, result) {

        if (err)console.log(err);

        if (vbean.parentId != 'root') {

            col.findAndModify(
                {_id: routers.ObjectID(vbean.parentId)}, [
                    ['isParent', 1]
                ],
                {$set: {"isParent": true}},
                function (err, doc) {
                    if (err)console.log(err);
                    res.json(doc);
                    pool.release(db);

                });

        } else {
            res.json(result);
            pool.release(db);
        }
    });
}

function updateAndModify(req,res,pool,db,acol) {

    var mcontent = req.body.menucontent;
    var name = req.body.name;
    var id = req.params.id;
    db.collection(menuname, function (err, mcol) {
        mcol.findAndModify({'id': 'onlyone'}, [], {$set: {content: mcontent}}
            , {w: 1}, function (err, doc) {

                acol.update({_id: routers.ObjectID(id)}
                    , {$set:{name: name}}
                    , {w: 1}
                    , function (err, result) {
                       pool.release(db);
                        res.json(result);
                    }
                );

            }
        );

    });

}

function updatesSort(req,res,pool,db,acol) {

    var mcontent = req.body.menucontent;
    var bean  = req.body.bean;
    db.collection(menuname, function (err, mcol) {
        mcol.findAndModify({'id': 'onlyone'}, [], {$set: {content: mcontent}}
            , {w: 1}, function (err, doc) {

                //console.log(bean);
                for(var kid in bean){
                    acol.update({_id:routers.ObjectID(kid)}, {$set:bean[kid]},{w: 0});
                }
                res.json({"success":true});
                setTimeout(function() {
                    pool.release(db);

                },1000);


            }
        );

    });

}

function updateArea(req,res,pool,db,acol) {

    var id = req.params.id;
    var area = req.body.area;
    //
    acol.findAndModify({area:area},[], {$set:{area:null}}, {w:1}, function(err, doc) {

         acol.findAndModify({_id:routers.ObjectID(id)},[],{$set:{area:area}}, {w:1}, function(err2, doc2) {

             pool.release(db);
             res.json(doc2);
         });


    });
}

function removeAndModify(req,res,pool,db,acol){
    var checkId = new RegExp("^[0-9a-fA-F]{24}$");
    var idz = req.body.idz;
    var mcontent = req.body.mcontent;
    var idzval = [];
    for(var i in idz){
        if(!checkId.test(idz[i]))continue;
        idzval.push(routers.ObjectID(idz[i]));
    }
    db.collection(menuname, function (err, mcol) {
        mcol.findAndModify({'id': 'onlyone'}, [], {$set: {content: mcontent}}
            , {w: 1}, function (err, doc) {

                acol.remove({_id : { $in: idzval}},function (err, result) {
                        pool.release(db);
                        res.json(result);
                    }
                );

            }
        );

    });
}


function findMainMenu(req,res,pool,db,acol) {

    db.collection(menuname, function (err, mcol) {
        mcol.findOne({'id': 'onlyone'}, {'fields': {content: 1}}, function (err, mdoc) {
            pool.release(db);
            res.json(mdoc);
        });
    });
}

module.exports = function (app, i18n) {
    routers.init(app, getRules(i18n));

    app.post('/' + cname + "/addm", function (req, res) {
        routers.proxyHttpWithDb(req, res, addAndModify);
    });
    app.post('/' + cname + "/updatem/:id", function (req, res) {
        routers.proxyHttpWithDb(req, res, updateAndModify);
    });
    app.post('/' + cname + "/update/area/:id", function (req, res) {
        routers.proxyHttpWithDb(req, res, updateArea);
    });

    app.post('/' + cname + "/updates/sort", function (req, res) {
        routers.proxyHttpWithDb(req, res, updatesSort);
    });
    app.post('/' + cname + "/removem/:id", function (req, res) {
        routers.proxyHttpWithDb(req, res, removeAndModify);
    });
    app.get('/mainmenu/onlyone', function (req, res) {
        routers.proxyHttpWithDb(req, res, findMainMenu);
    });

    app.get('/'+cname+'/static',function(req,res){
        res.render('articlec/static');
    });
}